package huriezy.quickcontacts.activities;

import huriezy.quickcontacts.R;
import huriezy.quickcontacts.SettingsActivity;
import huriezy.quickcontacts.activities.adapters.NewContactFragmentPagerAdapter;
import huriezy.quickcontacts.models.ContactController;
import huriezy.quickcontacts.models.LogDebug;
import huriezy.quickcontacts.models.interfaces.IContactManager;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;

public class NewContactFragmentActivity extends FragmentActivity {

//	private final String					showSocialPreference	= "show_social_pref";
//	private final String					showPicturePreference	= "show_picture_pref";
//	private final String					showInternetPreference	= "show_internet_pref";
//	private final String					showLocationPreference	= "show_location_pref";

	// View pager
	private ViewPager						viewPager;
	private NewContactFragmentPagerAdapter	fragmentAdapter;
	private ActionBar.TabListener			tabListener;

	// Managers
	private IContactManager					contactManager;

	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);

		ContactController instance = ContactController.getInstance();
		instance.initManagers(this);
		contactManager = instance.getContactManager(this);

		setContentView(R.layout.activity_new_contact_fragment);
		LogDebug.info(" --- onCreate for Activity NewContactFragmentActivity", getClass());
		initViews();
	}

	private void initViews() {
		// Init fragment view
		fragmentAdapter = new NewContactFragmentPagerAdapter(getSupportFragmentManager());
		viewPager = (ViewPager) findViewById(R.id.new_contact_view_pager);
		viewPager.setAdapter(fragmentAdapter);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			initActionBar();
		}
		else {
			initBasicMenu();
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		updateShownViews();
	}

	private void updateShownViews() {
//		if (fragmentAdapter != null) {
//			SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
//			Map<Class<? extends IContactFragment>, Boolean> newFragmentPreferences = new HashMap<Class<? extends IContactFragment>, Boolean>();
//			newFragmentPreferences.put(NameAndPhoneFragment.class, true);
//			newFragmentPreferences.put(SocialNetworkFragment.class, preferences.getBoolean(showSocialPreference, true));
//			newFragmentPreferences.put(PictureFragment.class, preferences.getBoolean(showPicturePreference, true));
//			newFragmentPreferences.put(EmailFragment.class, preferences.getBoolean(showInternetPreference, true));
//			newFragmentPreferences.put(LocationFragment.class, preferences.getBoolean(showLocationPreference, true));
//			
//			if(fragmentAdapter.hasPreferencesChanged(newFragmentPreferences)){
//				fragmentAdapter.setFragmentPreferences(newFragmentPreferences);
//			}
//		}
	}

	/**
	 * Create a standard menu for android version 2.x
	 */
	private void initBasicMenu() {
		viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				viewPager.setCurrentItem(position);
				fragmentAdapter.updateData(position);
				fragmentAdapter.saveContactData();
				// TODO handle a proper management for saving informations
				// between tables (ex : use saved bundle for this
				// application)
			}
		});
	}

	/**
	 * Create an action bar menu used for android version 3.x and further
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	public void initActionBar() {
		final ActionBar actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				actionBar.setSelectedNavigationItem(position);
			}
		});

		if (tabListener == null) {
			tabListener = new TabListener() {

				@Override
				public void onTabSelected(Tab tab, FragmentTransaction ft) {
					viewPager.setCurrentItem(tab.getPosition());
					fragmentAdapter.updateData(tab.getPosition());
					fragmentAdapter.saveContactData();
				}

				@Override
				public void onTabUnselected(Tab tab, FragmentTransaction ft) {
				}

				@Override
				public void onTabReselected(Tab tab, FragmentTransaction ft) {
				}
			};
		}

		Tab newTab = null;
		for (int index = 0; index < fragmentAdapter.getCount(); index++) {
			newTab = actionBar.newTab();
			newTab.setText(getPageTitle(index));
			newTab.setTabListener(tabListener);
			actionBar.addTab(newTab);
		}
	}

	private CharSequence getPageTitle(int index) {
		String result = null;
		Resources res = getResources();
		switch (index) {
			case 0:
				result = res.getString(R.string.tab_title_name_and_phone_text);
				break;
			case 1:
				result = res.getString(R.string.tab_title_social_network_text);
				break;
			case 2:
				result = res.getString(R.string.tab_title_picture_text);
				break;
			case 3:
				result = res.getString(R.string.tab_title_internet_text);
				break;
			case 4:
				result = res.getString(R.string.tab_title_address_text);
				break;
			default:
				break;
		}
		return result;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.new_contact, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int itemId = item.getItemId();
		if (R.id.menu_add_contact == itemId) {
			// Try to add new contact
			addContact();
			return true;
		}
		else if (R.id.menu_settings_contact == itemId) {
			// Show settings
			Intent intent = new Intent(NewContactFragmentActivity.this, SettingsActivity.class);
			startActivity(intent);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * Add a new contact to the device contact internal list.
	 */
	private void addContact() {

		fragmentAdapter.saveContactData();

		if (!contactManager.verifyCorrectContact()) {
			return;
		}

//		String name = contactManager.getContactData(IContactManager.NAME_TAG);
//		String number = contactManager.getContactData(IContactManager.NUMBER_TAG);
//
//		String existingContactId = contactManager.getExistingContactIdByNumber(number);
//		if (existingContactId != null) {
//			showExistingContactDialog(IContactManager.EXISTING_NUMBER, existingContactId);
//			return;
//		}
//		else {
//			existingContactId = contactManager.getExistingContactIdByName(name);
//			if (existingContactId != null) {
//				showExistingContactDialog(IContactManager.EXISTING_NAME, existingContactId);
//				return;
//			}
//		}

		boolean isCreated = contactManager.addCurrentContact();

		if (isCreated) {
			showContactAddedDialog();
		}
	}

	private void showContactAddedDialog() {
		// Build success message dialog
		String validationMessage = getResources().getString(R.string.success_add_contact_text);
		String validationTitle = getResources().getString(R.string.success_title_text);
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
		dialogBuilder.setCancelable(true);
		dialogBuilder.setMessage(validationMessage);
		dialogBuilder.setTitle(validationTitle);
		dialogBuilder.setPositiveButton("OK", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				fragmentAdapter.clearContactData();
			}
		});

		AlertDialog dialog = dialogBuilder.create();
		dialog.show();
	}

	/**
	 * Show an {@link AlertDialog} that ask the user if he want to replace an
	 * existing contact by the one he is creating.
	 * 
	 * @param type
	 * @param baseInfo
	 */
	@SuppressWarnings("unused")
	private void showExistingContactDialog(final int type, final String contactId) {
		Resources resources = getResources();

		final String contactFull = contactManager.getContactById(contactId);

		String name = null;
		String number = null;
		if (contactFull != null) {
			String[] contactSplit = contactFull.split(IContactManager.CONTACT_SEPARATOR);
			if (contactSplit != null && contactSplit.length >= 1) {
				name = contactSplit[0];
				number = contactSplit[1];
			}
		}

		String existingTitle = resources.getString(R.string.existing_contact_title_text);
		String replaceText = resources.getString(R.string.replace_button_text);
		String cancelText = resources.getString(R.string.cancel_button_text);
		StringBuilder existingMessage = new StringBuilder();
		if (type == IContactManager.EXISTING_NUMBER) {
			existingMessage.append(resources.getString(R.string.existing_contact_number_message_text1));
			existingMessage.append(number);
			existingMessage.append(resources.getString(R.string.existing_contact_number_message_text2));
			existingMessage.append(name);
			existingMessage.append(resources.getString(R.string.existing_contact_message_text3));
		}
		else if (type == IContactManager.EXISTING_NAME) {
			existingMessage.append(resources.getString(R.string.existing_contact_name_message_text1));
			existingMessage.append(name);
			existingMessage.append(resources.getString(R.string.existing_contact_name_message_text2));
			existingMessage.append(number);
			existingMessage.append(resources.getString(R.string.existing_contact_message_text3));
		}
		else {
			LogDebug.error("Cannot build alert dialog : incompatible type '" + type + "'", getClass());
			return;
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setCancelable(true);
		builder.setMessage(existingMessage.toString());
		if (existingTitle != null) {
			builder.setTitle(existingTitle);
		}
		if (replaceText != null) {
			builder.setPositiveButton(replaceText, new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					contactManager.replaceContact(contactId);
				}
			});
		}
		if (cancelText != null) {
			builder.setNegativeButton(cancelText, null);
		}

		AlertDialog dialog = builder.create();
		dialog.show();
	}

}